//
//  DownNumFileUtil.m
//  handbooklite
//
//  Created by bao_wsfk on 12-8-31.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//


#import "DownNumFileUtil.h"
#import "Config.h"
#import "JSONKit.h"

@implementation DownNumFileUtil

static DownNumFileUtil *_instance;
@synthesize fm =_fm;
@synthesize downnumFilePath =_downnumFilePath;

+ (id)newInstance{
    
    @synchronized(self){
        if (!_instance) {
            _instance =[[DownNumFileUtil alloc]init];
            [_instance setDownnumFilePath:[DOCUMENT_PATH stringByAppendingPathComponent:@"books/downnum.json"]];
        }
    return _instance;
    }
}

- (id)init{
    
    if (self =[super init]) {
        _fm =[[NSFileManager alloc] init];
    }
    return self;
}

- (void)dealloc{
    [super dealloc];
    _fm =nil;
    _downnumFilePath =nil;
}

- (void)setDownnumFilePath:(NSString *)downnumFilePath{
    _downnumFilePath =[downnumFilePath copy];
}

- (BOOL)isHasFile{
    return [_fm fileExistsAtPath:_downnumFilePath];
}

- (BOOL)isHasDownNum:(NSString *)downnum{
    
    if (![self isHasFile]) {
        return NO;
    }
    NSDictionary *downnumDic =[[NSData dataWithContentsOfFile:_downnumFilePath] objectFromJSONData];
    for (NSString *src in [downnumDic objectForKey:@"downnums"]) {
        if ([downnum isEqualToString:src]) {
            return YES;
        }
    }
    return NO;
}

- (BOOL)addDownNum:(NSString *)downnum{
    //判断是否存在 
    if (![self isHasFile]) {
        //不存在就创建
        NSDictionary *downnumDic =[NSDictionary dictionaryWithObject:
                                   [NSArray arrayWithObject:downnum]
                                                              forKey:@"downnums"];
        return [[downnumDic JSONData] writeToFile:_downnumFilePath atomically:YES];
        
    }else {
        //判断是否存在下载码
        if (![self isHasDownNum:downnum]) {
            //不存在就添加
            NSMutableDictionary *downnumDic =[[[NSData dataWithContentsOfFile:_downnumFilePath]
                                               objectFromJSONData] mutableCopy];
            
            NSMutableArray *downnums =[[downnumDic objectForKey:@"downnums"] mutableCopy];
            [downnums addObject:downnum];
            [downnumDic setObject:downnums forKey:@"downnums"];
            return [[downnumDic JSONData] writeToFile:_downnumFilePath atomically:YES];
        }
    }
    return NO;
}

- (NSArray *)downNums{
    return [(NSDictionary *)[[NSData dataWithContentsOfFile:_downnumFilePath]
                             objectFromJSONData]
                             objectForKey:@"downnums"];
}


@end
